<template>
  <div class="category-list">
    <div class="alert alert-danger" v-if="error">{{ error }}</div>
    <div class="alert alert-success" v-if="successMessage">{{ successMessage }}</div>
    
    <div class="action-bar">
      <button @click="showAddModal = true" class="add-btn">
        <i class="fas fa-plus"></i> 新建分类
      </button>
    </div>
    
    <div class="data-table">
      <table v-if="categories.length">
        <thead>
          <tr>
            <th>名称</th>
            <th>描述</th>
            <th>文章数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="category in categories" :key="category.id">
            <td>{{ category.name }}</td>
            <td>{{ category.description || '无描述' }}</td>
            <td>{{ category.postCount }}</td>
            <td class="actions-cell">
              <button 
                @click="editCategory(category)" 
                class="action-btn edit-btn"
                title="编辑分类"
              >
                <i class="fas fa-edit"></i>
              </button>
              <button 
                @click="confirmDelete(category)" 
                class="action-btn delete-btn"
                title="删除分类"
                :disabled="category.postCount > 0"
              >
                <i class="fas fa-trash-alt"></i>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div class="empty-state" v-else>
        <p>暂无分类</p>
        <button @click="showAddModal = true" class="create-btn">
          创建第一个分类
        </button>
      </div>
    </div>
    
    <!-- 添加/编辑分类模态框 -->
    <div class="modal" v-if="showAddModal || showEditModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑分类' : '添加分类' }}</h3>
          <button @click="closeModal" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitCategoryForm">
            <div class="form-group">
              <label for="name">分类名称</label>
              <input 
                type="text" 
                id="name" 
                v-model="categoryForm.name" 
                required
                placeholder="输入分类名称"
              />
            </div>
            
            <div class="form-group">
              <label for="description">分类描述</label>
              <textarea 
                id="description" 
                v-model="categoryForm.description" 
                rows="3"
                placeholder="输入分类描述（可选）"
              ></textarea>
            </div>
            
            <div class="modal-footer">
              <button type="button" @click="closeModal" class="cancel-btn">取消</button>
              <button type="submit" class="save-btn" :disabled="isSubmitting">
                {{ isSubmitting ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
    
    <!-- 删除确认对话框 -->
    <div class="modal" v-if="showDeleteModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>确认删除</h3>
          <button @click="showDeleteModal = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <p>确定要删除分类 "{{ categoryToDelete?.name }}" 吗？</p>
          <p class="warning">此操作不可恢复！</p>
          <p v-if="categoryToDelete?.postCount > 0" class="warning">
            无法删除包含文章的分类，请先移除或重新分类文章。
          </p>
        </div>
        <div class="modal-footer">
          <button @click="showDeleteModal = false" class="cancel-btn">取消</button>
          <button 
            @click="deleteCategory" 
            class="confirm-btn" 
            :disabled="isDeleting || categoryToDelete?.postCount > 0"
          >
            {{ isDeleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { categoryService } from '../../../services';

export default {
  setup() {
    // 状态
    const categories = ref([]);
    const error = ref('');
    const successMessage = ref('');
    
    // 模态框状态
    const showAddModal = ref(false);
    const showEditModal = ref(false);
    const showDeleteModal = ref(false);
    const isSubmitting = ref(false);
    const isDeleting = ref(false);
    
    // 表单和删除相关状态
    const categoryForm = reactive({
      id: null,
      name: '',
      description: ''
    });
    const categoryToDelete = ref(null);
    
    // 加载分类列表
    const loadCategories = async () => {
      try {
        error.value = '';
        const response = await categoryService.getAllCategories();
        categories.value = response.categories || [];
      } catch (err) {
        error.value = '加载分类失败';
        console.error('加载分类失败:', err);
      }
    };
    
    // 编辑分类
    const editCategory = (category) => {
      categoryForm.id = category.id;
      categoryForm.name = category.name;
      categoryForm.description = category.description || '';
      showEditModal.value = true;
    };
    
    // 确认删除
    const confirmDelete = (category) => {
      categoryToDelete.value = category;
      showDeleteModal.value = true;
    };
    
    // 删除分类
    const deleteCategory = async () => {
      if (!categoryToDelete.value || categoryToDelete.value.postCount > 0) return;
      
      try {
        isDeleting.value = true;
        
        await categoryService.deleteCategory(categoryToDelete.value.id);
        
        // 删除成功
        successMessage.value = '分类删除成功';
        showDeleteModal.value = false;
        
        // 重新加载分类列表
        await loadCategories();
        
        // 3秒后清除成功消息
        setTimeout(() => {
          successMessage.value = '';
        }, 3000);
      } catch (err) {
        error.value = err.response?.data?.message || '删除分类失败';
        console.error('删除分类失败:', err);
      } finally {
        isDeleting.value = false;
      }
    };
    
    // 提交分类表单
    const submitCategoryForm = async () => {
      try {
        isSubmitting.value = true;
        error.value = '';
        successMessage.value = '';
        
        if (showEditModal.value) {
          // 更新分类
          await categoryService.updateCategory(categoryForm.id, {
            name: categoryForm.name,
            description: categoryForm.description
          });
          successMessage.value = '分类更新成功';
        } else {
          // 创建分类
          await categoryService.createCategory({
            name: categoryForm.name,
            description: categoryForm.description
          });
          successMessage.value = '分类创建成功';
        }
        
        // 关闭模态框
        closeModal();
        
        // 重新加载分类列表
        await loadCategories();
        
        // 3秒后清除成功消息
        setTimeout(() => {
          successMessage.value = '';
        }, 3000);
      } catch (err) {
        error.value = err.response?.data?.message || (showEditModal.value ? '更新分类失败' : '创建分类失败');
        console.error(showEditModal.value ? '更新分类失败:' : '创建分类失败:', err);
      } finally {
        isSubmitting.value = false;
      }
    };
    
    // 关闭模态框
    const closeModal = () => {
      showAddModal.value = false;
      showEditModal.value = false;
      
      // 重置表单
      categoryForm.id = null;
      categoryForm.name = '';
      categoryForm.description = '';
    };
    
    // 初始化
    onMounted(() => {
      loadCategories();
    });
    
    return {
      categories,
      error,
      successMessage,
      showAddModal,
      showEditModal,
      showDeleteModal,
      categoryForm,
      categoryToDelete,
      isSubmitting,
      isDeleting,
      editCategory,
      confirmDelete,
      deleteCategory,
      submitCategoryForm,
      closeModal
    };
  }
}
</script>

<style scoped>
.category-list {
  width: 100%;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.add-btn {
  padding: 10px 15px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.add-btn:hover {
  background-color: #218838;
}

.data-table {
  margin-bottom: 20px;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e9ecef;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.actions-cell {
  white-space: nowrap;
}

.action-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 5px;
  color: white;
}

.edit-btn {
  background-color: #007bff;
}

.delete-btn {
  background-color: #dc3545;
}

.edit-btn:hover { background-color: #0069d9; }
.delete-btn:hover { background-color: #c82333; }

.delete-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.empty-state {
  text-align: center;
  padding: 30px;
  color: #6c757d;
}

.create-btn {
  display: inline-block;
  margin-top: 10px;
  padding: 8px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.create-btn:hover {
  background-color: #0069d9;
}

.alert {
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.alert-danger {
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  color: #721c24;
}

.alert-success {
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
  color: #155724;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6c757d;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 16px;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.warning {
  color: #dc3545;
  font-weight: bold;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn, 
.save-btn,
.confirm-btn {
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.save-btn {
  background-color: #28a745;
  color: white;
}

.confirm-btn {
  background-color: #dc3545;
  color: white;
}

.save-btn:disabled,
.confirm-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}
</style> 